﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Models;
using Microsoft.Win32;
using System.Xml.Linq;
using System.ServiceProcess;

namespace CC.Net_Creator
{
    public partial class CCCreator : Form
    {

        #region Properties
        string _folderPath = string.Empty;
        CCPaths _paths = null;
        List<string> _testAssemblies = null;
        #endregion

        #region Constructor
        public CCCreator()
        {
            InitializeComponent();
            _paths = new CCPaths() { Queue = "Q1" };
            _testAssemblies = new List<string>();
        }

        #endregion

        #region Methods
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
            {
                _folderPath = folderBrowserDialog1.SelectedPath;
                txtPath.Text = _folderPath;
                ScanDirectory(_folderPath);
            }

        }

        private void ScanDirectory(string _folderPath)
        {
            DirectoryInfo di = new DirectoryInfo(_folderPath);
            var files = di.GetFiles();

            var solutioName = (from f in files
                                  where f.Name.Contains(".sln")
                                  select f).FirstOrDefault();
            var FxCopName = (from f in files
                                where f.FullName.Contains(".FxCop")
                                select f).FirstOrDefault();
            if (solutioName == null)
            {
                MessageBox.Show("Folder Contains no Solution File");
                folderBrowserDialog1.Reset();
                txtPath.Text = "";
            }
            else if (FxCopName == null)
            {
                MessageBox.Show("Folder Contains no Fxcop Project");
            }
            else
            {
                if (!string.IsNullOrEmpty(solutioName.Name))
                {
                    _paths.SolutionName = solutioName.Name;
                }              
                if (!string.IsNullOrEmpty(FxCopName.Name))
                {
                    _paths.FxcopProjectPath = FxCopName.Name;
                }              
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "dll files (*.dll)|*.dll";
            openFileDialog1.Multiselect = true;
            openFileDialog1.ShowDialog();
            foreach (var name in openFileDialog1.FileNames)
            {
                if (!string.IsNullOrEmpty(name))
                {
                    _paths.NunitAssemblies.Add(new XElement("assembly",name));
                    cmbAssemblies.Items.Add(name);
                }
            }
            if (cmbAssemblies.Items.Count > 0)
            {
                cmbAssemblies.SelectedIndex = 0;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            _paths.ProjectName = txtProjectName.Text;
        }
     

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            Stream resourceStream;
            System.Reflection.Assembly assemb = System.Reflection.Assembly.GetExecutingAssembly();
            resourceStream = assemb.GetManifestResourceStream("CC.Net_Creator.Resources.Paths.xml");
            Populate(resourceStream);
            CreateConfig cc = new CreateConfig();
           var nullProperties = _paths.CheckForNulls();
           if (nullProperties.Count == 0)
           {
               bool saved = cc.CreatDoc(_paths);             
               ReportSaved(saved);
           }
           else
           {
                MessageBox.Show(string.Format("The following information need to be provide: \n{0}",formatNull(nullProperties)));              
           }
            
        }
     

        private static string formatNull(List<string> nullProperties)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in nullProperties)
            {
                sb.Append(string.Format("{0}\n",item));
            }
            return sb.ToString();
        }

        private void ReportSaved(bool saved)
        {
            switch (saved)
            {
                case true:
                    rtxtMessages.Text += "Configuration saved!";
                    break;
                case false:
                    rtxtMessages.Text += "Configuration was not saved";
                    break;
                default:
                    break;
            }
        }

        private void Populate(Stream resourceStream)
        {
            XDocument xml = XDocument.Load(resourceStream);
            var paths = from i in xml.Elements("paths").Elements("path")
                        select i;
            foreach (var item in paths)
            {
                var att = item.Attributes();
                foreach (var attribute in att)
                {
                    switch (attribute.Value)
                    {
                        case "Logs":
                            _paths.ProjectLogs = item.Value;
                            break;
                        case "SvnUrl":
                            _paths.SvnURL = item.Value;
                            break;
                        case "SvnExecutable":
                            _paths.SvnExecutable = item.Value;
                            break;
                        case "MSbuildExecutable":
                            _paths.MSbuildExecutable = item.Value;
                            break;
                        case "FxCopExecutable":
                            _paths.FxCopExecutable = item.Value;
                            break;
                        case "NunitExecutable":
                            _paths.NunitExecutable = item.Value;
                            break;
                        case "CCPath":
                            _paths.CCPath = item.Value;
                            break;
                        default:
                            break;
                    }
                }
            }

        }


        private void txtPath_TextChanged(object sender, EventArgs e)
        {
            txtPath.Text = folderBrowserDialog1.SelectedPath;
            _paths.ProjectDirectory = folderBrowserDialog1.SelectedPath;
            rtxtMessages.Text += string.Format("Solution path: {0}\n", folderBrowserDialog1.SelectedPath);
        }
      

        private void maskedTextBox2_TextChanged(object sender, EventArgs e)
        {
            _paths.QueuePriority = maskedtxtQueuePriority.Text;
        }

        private void txtProjectName_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtProjectName.Text))
            {
                rtxtMessages.Text += string.Format("Project name: {0}\n", _paths.ProjectName);
            }
        }

        private void cmbBuildType_SelectedValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cmbBuildType.SelectedItem.ToString()))
            {
                _paths.BuildType = cmbBuildType.SelectedText;
                rtxtMessages.Text += string.Format("Buid type: {0}\n", cmbBuildType.SelectedItem.ToString());
            }
        }


        private void maskedtxtQueuePriority_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(maskedtxtQueuePriority.Text))
            {
                _paths.QueuePriority = maskedtxtQueuePriority.Text;                                
                rtxtMessages.Text += string.Format("Queue Priority : {0} Queue : {1}\n", _paths.QueuePriority, _paths.Queue);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cmbAssemblies.Items.Remove(cmbAssemblies.SelectedItem);
            if (cmbAssemblies.Items.Count.Equals(0))
            {
                cmbAssemblies.Text = "";
            }
            else
            {
                cmbAssemblies.SelectedIndex = 0;
            }
            
        }
        #endregion
      
    }
}
